import 'package:flutter/material.dart';
import 'package:tencent_cloud_chat_sdk/enum/message_elem_type.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_image_elem.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_message.dart';
import 'package:video_ducafecat_flutter_v3/common/index.dart';

/// 图片消息
class MsgImageElemWidget extends StatefulWidget {
  const MsgImageElemWidget({
    super.key,
    required this.message,
  });

  /// 消息
  final V2TimMessage message;

  @override
  State<MsgImageElemWidget> createState() => _MsgImageElemWidgetState();
}

class _MsgImageElemWidgetState extends State<MsgImageElemWidget> {
  /// 消息 msdId
  late String? msgID;

  /// 图片消息
  late V2TimImageElem stateElement;

  @override
  void initState() {
    super.initState();

    msgID = widget.message.msgID;
    stateElement = widget.message.imageElem!;

    downloadMessageDetailAndSave();
  }

  // 下载 url 和 文件
  downloadMessageDetailAndSave() async {
    if (msgID != null && msgID != '') {
      // 拉取完整数据
      var localUrl = stateElement.imageList?.first?.localUrl;
      if (localUrl == null || localUrl == '') {
        final response = await IMService.to.manager
            .getMessageOnlineUrl(msgID: widget.message.msgID!);
        if (response.data != null) {
          Future.delayed(const Duration(microseconds: 10), () {
            if (mounted) {
              setState(() => stateElement = response.data!.imageElem!);
            }
          });
        }
      }
      // 下载图片
      if (!PlatformUtils().isWeb) {
        for (int i = 0; i < (stateElement.imageList?.length ?? 0); i++) {
          var imgEle = stateElement.imageList?[i];
          var localUrl = imgEle?.localUrl;
          if (localUrl == null || localUrl == '') {
            await IMService.to.manager.downloadMessage(
              msgID: widget.message.msgID!,
              messageType: MessageElemType.V2TIM_ELEM_TYPE_IMAGE, // 消息类型
              imageType: imgEle?.type, // 图片类型
            );
          }
        }
      }
    }
  }

  // 图片 Url
  String? getImgUrl(V2TimImageTypesEnum imgType) {
    var imgElem = stateElement.imageList
        ?.firstWhere((element) => element?.type == imgType.index);
    if (imgElem != null) {
      return imgElem.url ?? "";
    }
    return null;
  }

  // 图片本地地址
  String? getImgLocalUrl(V2TimImageTypesEnum imgType) {
    var imgElem = stateElement.imageList
        ?.firstWhere((element) => element?.type == imgType.index);
    if (imgElem != null) {
      return imgElem.localUrl ?? "";
    }
    return null;
  }

  // 远程图片
  // *第一次时候使用
  Widget _buildRemoteImage(BuildContext context) {
    var imageUrl = getImgUrl(V2TimImageTypesEnum.small);
    var imageBigUrl = getImgUrl(V2TimImageTypesEnum.big);

    // 空返回占位
    if (imageUrl == null || imageUrl.isEmpty) {
      return const SizedBox.shrink();
    }

    // 图片
    return ImageWidget.url(
      imageUrl,
      width: 120,
    ).onTap(() {
      Navigator.push(context, MaterialPageRoute(builder: (context) {
        return GalleryWidget(
          imgUrl: imageBigUrl,
        );
      }));
    });
  }

  // 之后取，本地图片
  Widget _buildLocalImage(BuildContext context) {
    var imageUrl = getImgLocalUrl(V2TimImageTypesEnum.small);
    var imageBigUrl = getImgLocalUrl(V2TimImageTypesEnum.big);

    // 空返回占位
    if (imageUrl == null || imageUrl.isEmpty) {
      return const SizedBox.shrink();
    }

    // 图片
    return ImageWidget.file(
      imageUrl,
      width: 120,
    ).onTap(() {
      Navigator.push(context, MaterialPageRoute(builder: (context) {
        return GalleryWidget(
          imgLocaPath: imageBigUrl,
        );
      }));
    });
  }

  // 主视图
  Widget _buildView(BuildContext context) {
    // 刚发消息本地图
    if (msgID == null) {
      return ImageWidget.file(
        stateElement.path ?? "",
        width: 120,
      );
    }

    // 01 本地图片优先显示
    var localUrl = getImgLocalUrl(V2TimImageTypesEnum.small);
    if (localUrl != null && localUrl.isNotEmpty) {
      return _buildLocalImage(context);
    }

    // 02 远程图片
    return _buildRemoteImage(context);
  }

  @override
  Widget build(BuildContext context) {
    return _buildView(context);
  }
}
